﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using Demo.Model.EntityModels;
using Demo.Business.ViewServices.Abstract;

namespace Demo.Framework
{
    public class RequiredIfAttribute : ValidationAttribute
    {
        //private RequiredAttribute _innerAttribute = new RequiredAttribute();

        public string DependentProperty { get; set; }
        public string TargetProperty { get; set; }

        public RequiredIfAttribute(string dependentProperty, string targetProperty)
        {
            this.DependentProperty = dependentProperty;
            this.TargetProperty = targetProperty;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            // get a reference to the property this validation depends upon
            var containerType = validationContext.ObjectInstance.GetType();
            var fielddepent = containerType.GetProperty(this.DependentProperty);
            var fieldtarget = containerType.GetProperty(this.TargetProperty);
            if (fielddepent != null && fieldtarget != null)
            {
                // get the value of the dependent property
                var dependentvalue = fielddepent.GetValue(validationContext.ObjectInstance, null);
                var targetvalue = fieldtarget.GetValue(validationContext.ObjectInstance, null);
                // compare the value against the target value
                if (dependentvalue == null || targetvalue == null || CheckAlreadyExists((int)dependentvalue, (DateTime)targetvalue))
                {
                    //// match => means we should try validating this field 
                    //if (!_innerAttribute.IsValid(value))
                    //    // validation failed - return an error
                    return new ValidationResult(this.ErrorMessage, new[] { validationContext.DisplayName });
                }
            }

            return ValidationResult.Success;
        }

        private bool CheckAlreadyExists(int sOFID, DateTime effectiveDate)
        {
            IHomeViewService homeViewService =  Demo.Business.NinjectFactory.Get<IHomeViewService>();
            //List<InterestRate> listSourceOfFund = homeViewService.ServiceContext.InterestRateService.GetList();
            //foreach (InterestRate item in listSourceOfFund)
            //{
            //    if (item.SOFID == sOFID && DateTime.Compare(item.EffectiveDate, effectiveDate) == 0)
            //    {
            //        return true; 
            //    }
            //}
            return false;
        }
    }
}
